🐌
달팽이 배열
February 04, 2023
달팽이 배열?

snail array.. 달팽이 집 같이 숫자를 배치하고 구분한 배열
어디에 사용하는지는 모르겠지만 귀엽게 생긴 배열이다.
개념은 상하좌우 로 움직이면서 숫자를 넣는 게임기와 같다.
좌상단(시작점) => 우상단 => 우하단 => 좌하단 => 좌상단의 반복 을 구현하면 된다.
구현
function solution(n){
// 모두를 담을 배열
const result = []
// 배열 안 배열
for(let i = 0; i < n; i++){
result.push([])
}
// 이동
let count = 1
let startColumn = 0
let endColumn = n-1
let startRow = 0
let endRow = n-1
// 배열에 값 추가
while(startColumn <= endColumn && startRow <= endRow){
// 좌상 => 좌상
for(let i = startColumn; i <= endColumn; i++){
result[startRow][i] = count
count++
}
startRow++
// 우상 => 우하
for(let i = startRow; i <= endRow; i++){
result[i][endColumn] = count
count++
}
endColumn--
// 우하 => 좌하
for(let i = endColumn; i >= startColumn; i--){
result[endRow][i] = count
count++
}
endRow--
// 좌하 => 좌상
for(let i = endRow; i >= startRow; i--){
result[i][startColumn] = count
count++
}
startColumn++
}
return result
}
const n = 4
solution(n)
// [
// [ 1, 2, 3, 4 ],
// [ 12, 13, 14, 5 ],
// [ 11, 16, 15, 6 ],
// [ 10, 9, 8, 7]
// ]